package com.lvmama.service.system.impl;

import com.lvmama.common.constants.Constants;
import com.lvmama.common.result.CodeMessage;
import com.lvmama.common.result.Result;
import com.lvmama.common.utils.BeanConvertionHelp;
import com.lvmama.common.utils.CheckParamsUtil;
import com.lvmama.common.utils.RandomUUIDUtil;
import com.lvmama.dao.rhino.system.RoleDao;
import com.lvmama.dao.rhino.system.RoleMenuDao;
import com.lvmama.pojo.base.Page;
import com.lvmama.pojo.dto.rhino.system.*;
import com.lvmama.pojo.entity.rhino.system.Role;
import com.lvmama.pojo.entity.rhino.system.RoleMenu;
import com.lvmama.service.system.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;
    @Autowired
    private RoleMenuDao roleMenuDao;

    @Override
    public Result<List<Role>> queryRoleList(RoleQueryDTO query) {
        log.info("queryRoleList start. query:{}",
                ToStringBuilder.reflectionToString(query, ToStringStyle.DEFAULT_STYLE));
        List<Role> roleList = new ArrayList<>();
        try {
            RoleQuery example = new RoleQuery();
            RoleQuery.Criteria criteria = example.createCriteria().andDelFlagEqualTo(Constants.DEL_FLAG);
            if (StringUtils.isNotBlank(query.getName())) {
                criteria.andNameEqualTo(query.getName());
            }
            roleList = roleDao.selectByExample(example);
        } catch (Exception e) {
            log.error("queryRoleList error:", e.getMessage(), e);
            return Result.error(CodeMessage.SERVER_ERROR);
        }
        log.info("queryRoleList end.");
        return Result.success(roleList);
    }

    @Override
    public Result<Page<Role>> queryRolePage(RoleQueryDTO query) {
        log.info("queryRolePage start. query:{}", ToStringBuilder.reflectionToString(query, ToStringStyle.DEFAULT_STYLE));
        Page<Role> page = new Page<>();
        try {
            RoleQuery example = new RoleQuery();
            example.createCriteria().andDelFlagEqualTo(Constants.DEL_FLAG);
            int count = roleDao.countByExample(example);
            example.setPageNo(query.getPageNo());
            example.setPageSize(query.getLimit());
            List<Role> rows = roleDao.selectByExample(example);
            //设置结果及分页对象
            if (null != rows && !rows.isEmpty()) {
                log.info("queryRolePage results:{}", count);
                log.info("queryRolePage rows:{}",ToStringBuilder.reflectionToString(rows, ToStringStyle.DEFAULT_STYLE));
                page.setStart(query.getStart());
                page.setResults(count);
                page.setLimit(query.getLimit());
                page.setPage(query.getPage());
                page.setPageNo(query.getPageNo());
                page.setRows(rows);
                page.setIsSuccess(true);
            }
            //分页展示
            page.pageView("/role/roleList", null);
        } catch (Exception e) {
            log.error("queryRolePage error:{}", e.getMessage(), e);
            page.setError("数据库查询角色分页失败");
            page.setErrorCode(e.getMessage());
            page.setErrorCode(e.getMessage());
            page.setResults(0);
        }
        log.info("queryRolePage end.");
        return Result.success(page);
    }

    @Override
    public Result<List<Role>> queryRoleInfo(RoleQueryDTO query) {
        log.info("queryRoleList start. query:{}",
                ToStringBuilder.reflectionToString(query, ToStringStyle.DEFAULT_STYLE));
        List<Role> roleList = new ArrayList<>();
        try {
            RoleQuery example = new RoleQuery();
            RoleQuery.Criteria criteria = example.createCriteria().andDelFlagEqualTo(Constants.DEL_FLAG);
            if (StringUtils.isNotBlank(query.getName())) {
                criteria.andNameEqualTo(query.getName());
            }
            roleList = roleDao.selectByExample(example);
        } catch (Exception e) {
            log.error("queryRoleList error:", e.getMessage(), e);
            return Result.error(CodeMessage.SERVER_ERROR);
        }
        log.info("queryRoleList end.");
        return Result.success(roleList);
    }

    @Override
    public Result<Role> queryRoleById(String id) {
        log.info("queryRoleById start id:{}", id);
        Role role =new Role();
        try {
             role = roleDao.selectByPrimaryKey(id);
        } catch (Exception e) {
            log.error("queryRoleById error:{}", e.getMessage(), e);
            return Result.error(CodeMessage.SERVER_ERROR);
        }
        log.info("queryRoleById end.");
        return Result.success(role);
    }

    @Override
    public Result<Integer> updateRoleByRoleDTO(RoleDTO roleDTO)  {
        log.info("updateRoleByRoleDTO start.menuDTO:{}",
                ToStringBuilder.reflectionToString(roleDTO, ToStringStyle.DEFAULT_STYLE));
        int count = 0;
        try {
            CheckParamsUtil.check(roleDTO, RoleDTO.class, "id");
            Role record = BeanConvertionHelp.copyBeanFieldValue(Role.class, roleDTO);

            count = roleDao.updateByPrimaryKeySelective(record);
            //编辑角色菜单
            //先查询出该角色已有的菜单
            RoleMenuQuery example = new RoleMenuQuery();
            example.createCriteria().andRoleIdEqualTo(roleDTO.getId());
            List<RoleMenu> roleMenus = roleMenuDao.selectByExample(example);
            String[] ids = new String[0];
            if (StringUtils.isNotBlank(roleDTO.getMenuIds())) {
                ids = roleDTO.getMenuIds().split(",");
            }
            List<String> roleMenuIds = Arrays.asList(ids);

            //删除sys_role_menu
            roleMenuDao.deleteRoleMenu(roleDTO.getId());
            if(roleMenuIds!=null&&roleMenuIds.size()>0){
                RoleMenuBatchDO batchDO = new RoleMenuBatchDO();
                batchDO.setRoleMenuIds(roleMenuIds);
                batchDO.setRoleId(record.getId());
                roleMenuDao.insertBatch(batchDO);
            }

        } catch (Exception e) {
            log.error("updateRoleByRoleDTO Exception:{}", e.getMessage(), e);
            return Result.error(CodeMessage.SERVER_ERROR);
        }
        log.info("updateRoleByRoleDTO end, {} row(s) affected", count);
        return Result.success(count);
    }

    @Override
    public Result<Integer> saveRoleByRoleDTO(RoleDTO roleDTO)  {
        log.info("saveRoleByRoleDTO start.menuDTO:{}",
                ToStringBuilder.reflectionToString(roleDTO, ToStringStyle.DEFAULT_STYLE));
        int count =0;
        try {
            Role record = BeanConvertionHelp.copyBeanFieldValue(Role.class, roleDTO);
            record.setId(RandomUUIDUtil.getRadomUUID());
            record.setDelFlag(Constants.DEL_FLAG);
             count = roleDao.insertSelective(record);
            //保存角色菜单
            if (StringUtils.isNotBlank(roleDTO.getMenuIds())) {
                String[] ids = new String[0];
                if (StringUtils.isNotBlank(roleDTO.getMenuIds())) {
                    ids = roleDTO.getMenuIds().split(",");
                }
                List<String> roleMenuIds = Arrays.asList(ids);
                RoleMenuBatchDO batchDO = new RoleMenuBatchDO();
                batchDO.setRoleMenuIds(roleMenuIds);
                batchDO.setRoleId(record.getId());
                count += roleMenuDao.insertBatch(batchDO);
            }
            log.info("saveRoleByRoleDTO {} rows affects", count);
        } catch (Exception e) {
            log.error("saveRoleByRoleDTO Exception:{}", e.getMessage(), e);
            return Result.error(CodeMessage.SERVER_ERROR);
        }
        log.info("saveRoleByRoleDTO end, {} row(s) affected", count);
        return Result.success(count);
    }

    @Override
    public Result<Boolean> deleteRoleById(String id)  {
        log.info("deleteRoleById start. id:{}", id);
        try {
            Role record = new Role();
            record.setId(id);
            record.setDelFlag("1");
            int count = roleDao.updateByPrimaryKeySelective(record);
        } catch (Exception e) {
            log.error("deleteRoleById Exception:{}", e.getMessage(), e);
            return Result.error(CodeMessage.SERVER_ERROR);
        }
        log.info("deleteRoleById end.");
        return Result.success(true);
    }

    @Override
    public Result<Role> selectRoleMenusByRoleId(String roleId) {
        log.info("selectRoleMenusByRoleId start roleId:{}", roleId);
        Role role = new Role();
        try {
             role = roleDao.selectRoleMenusByRoleId(roleId);
        } catch (Exception e) {
            log.error("selectRoleMenusByRoleId error:{}", e.getMessage(), e);
            return Result.error(CodeMessage.SERVER_ERROR);
        }
        log.info("selectRoleMenusByRoleId end.");
        return Result.success(role);
    }
}
